from PyQt6.QtCore import QObject, QThread, pyqtSignal
from utils.SpiderUtils import AudioSpider
import os
from pygame import mixer as pygame_mixer

class SpiderThread(QThread):
    download_finished_signal = pyqtSignal(str)
    download_update_signal = pyqtSignal(int)
    def __init__(self, parent=None):
        super().__init__(parent)
        self.spider = AudioSpider()
        self.saved_dir = "./audios/"



    def run(self):
        if len(self.parameters) == 3:
            main_tableWidget, all_rows_num, people_name = self.parameters
            try:
                for row_idx in range(all_rows_num):
                    text = main_tableWidget.item(row_idx, 1).text() #  表格从0 开始
                    
                    saved_path = os.path.join(self.saved_dir, f"{row_idx+1}.mp3")  # 下载的从1开始
                    self.spider.download_audio(text, people_name, saved_path)

                    self.download_update_signal.emit(row_idx) # 完成的index

                self.download_finished_signal.emit("下载成功，单击即可播放")
            except Exception as e:
                self.download_finished_signal.emit(e.__str__())
        
        else:
            text_idx, text, people_name, _ = self.parameters
            try:
                saved_path = os.path.join(self.saved_dir, f"{text_idx+1}.mp3")  # 下载的从1开始
                self.spider.download_audio(text, people_name, saved_path)

                self.download_update_signal.emit(text_idx) # 完成的index
                self.download_finished_signal.emit("下载成功，单击即可播放")
            except Exception as e:
                self.download_finished_signal.emit(e.__str__())

        


class MainController():
    def __init__(self) -> None:
        self.spider_thread = SpiderThread()
        
    def download_one_mp3(self, text_idx, text, people_name):
        self.spider_thread.parameters = (text_idx, text, people_name, "")
        self.spider_thread.start()

    def download_all_mp3(self, main_tableWidget, all_rows_num, people_name):
        self.spider_thread.parameters = (main_tableWidget, all_rows_num, people_name)
        # 启动线程执行下载任务
        self.spider_thread.start()

    def play_music(self, mp3_idx):
        mp3_path = os.path.join(self.spider_thread.saved_dir, f"{mp3_idx}.mp3")
        if not os.path.exists(mp3_path):
            return
        pygame_mixer.music.load(mp3_path)
        pygame_mixer.music.play()

    def init_pygame_player(self):
        pygame_mixer.init()
    
    def release_pygame_player(self):
        pygame_mixer.quit()

    def remove_music(self, mp3_id):
        self.release_pygame_player()

        to_del_mp3_path = os.path.join(self.spider_thread.saved_dir, f"{mp3_id}.mp3")

        if os.path.exists(to_del_mp3_path):
            os.remove(to_del_mp3_path)

        mp3_list = os.listdir(self.spider_thread.saved_dir)
        mp3_list = sorted(mp3_list, key=lambda x: int(x.split(".mp3")[0]))  # 正序的

        for old_name in mp3_list:
            old_num = old_name.split(".mp3")[0]
            if int(old_num) <= mp3_id:
                continue
            new_num = str(int(old_num) - 1)
            os.rename(os.path.join(self.spider_thread.saved_dir, old_name), os.path.join(self.spider_thread.saved_dir, f"{new_num}.mp3"))

        self.init_pygame_player()

        
    def insert_music(self, mp3_id):
        self.release_pygame_player()
        mp3_list = os.listdir(self.spider_thread.saved_dir)
        inverse_mp3_list = sorted(mp3_list, key=lambda x: int(x.split(".mp3")[0]), reverse=True)


        for old_name in inverse_mp3_list:
            old_num = old_name.split(".mp3")[0]
            if int(old_num) < mp3_id:
                break
            new_num = str(int(old_num) + 1)
            os.rename(os.path.join(self.spider_thread.saved_dir, old_name), os.path.join(self.spider_thread.saved_dir, f"{new_num}.mp3"))


        self.init_pygame_player()



